import React, {FC, useCallback, useMemo, useRef, useState} from "react";
import {Spin} from "antd";
import "./css/IssuePage.less";
import {Panel, PanelGroup} from "react-resizable-panels";
import CTable from "../../global/table/CTable";
import ListPage from "../common/ListPage.tsx";

interface IssuePageProps {
    leftProps: any,
    rowKey: string,
    viewName: string,
    isLazyData: boolean,
    isTreeTable: boolean,
    tableApi: any
}

const IssuePage: FC<IssuePageProps> = (props) => {
    const cTable = useRef();

    const [loading, setLoading] = useState(false),
        [selectRow, setSelectRow] = useState(null);

    const otherRenderFn = useCallback(() => {
        return {}
    })

    const getLeftWidth = useCallback((num) => {
        return num / window.innerWidth * 100;
    }, []);

    const handleSelect = useCallback((selectRows) => {
        if (selectRows.length) {
            setSelectRow(selectRows[0])
        }
    }, [])

    const renderIssuePageTree = useMemo(() => {
        const {leftProps = {}} = props, {rowKey = "id", isLazyData, isTreeTable, tableApi = {}, viewName} = leftProps;
        const size = getLeftWidth(250);
        const tableHeight = document.querySelector('.sf_core_main_layout_content_main_content').offsetHeight;
        return (
            <Panel defaultSize={size} minSize={size} className="sf_core_issue_page_tree">
                <CTable
                    init={cTable}
                    rowKey={rowKey}
                    isLazyData={isLazyData}
                    isTreeTable={isTreeTable}
                    tableApi={tableApi}
                    view={viewName}
                    height={tableHeight}
                    hasCheckbox={false}
                    isSideBar={false}
                    onSelectChange={handleSelect}
                />
            </Panel>
        )
    }, [props]);

    const renderIssuePageTable = useMemo(() => {
        if (!selectRow) {
            return null
        }
        let listProps = {
            ...props,
            row: selectRow,
            leftProps: undefined
        }
        return (
            <ListPage {...listProps} otherRenderFn={otherRenderFn}/>
        )
    }, [selectRow]);

    const renderIssuePage = useMemo(() => {
        return (
            <Spin spinning={loading} wrapperClassName="sf_core_issue_page">
                <PanelGroup direction="horizontal">
                    {renderIssuePageTree}
                    <Panel className="sf_core_issue_page_table">
                        {renderIssuePageTable}
                    </Panel>
                </PanelGroup>
            </Spin>
        )
    }, [loading, props, selectRow]);

    return (renderIssuePage);
};

export default React.memo(IssuePage);